<template>
  <div style="padding: 30px">
    <!-- 搜索和新增管理员 -->

    <div class="function-lan" style="width: 100%">
      <label for="roleslist" style="margin-right: 10px">角色名称:</label>
      <div class="search-for">
        <el-input
          class="search-for-ipt"
          clearable
          @clear="getRolesList"
          prefix-icon="el-icon-search"
          v-model="queryInfo.query"
          placeholder="请输入标题进行搜索"
        ></el-input>
      </div>
      <!-- 搜索按钮 -->
      <div class="search-btn" @click="searchFor">
        <Buttons :text="text3"></Buttons>
      </div>
      <div class="add-new-manager">
        <!-- 添加管理员按钮 -->
        <div class="add-manager-btn" @click="addRoleDialog">
          <Buttons :text="text1"></Buttons>
        </div>
      </div>
    </div>

    <!-- table区域 -->
    <el-table
      :data="roleslist"
      style="margin-top: 40px"
      v-loading="listLoading"
      border
      stripe
      fit
      highlight-current-row
    >
      <el-table-column label="角色编号" prop="id"></el-table-column>
      <el-table-column label="角色名称" prop="name"></el-table-column>
      <el-table-column label="角色权限" prop="nameZh"></el-table-column>
      <el-table-column
        :formatter="dateFormat"
        label="创建时间"
        width="180px"
        align="center"
        prop="create_time"
      >
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template slot-scope="scope">
          <!-- 添加权限 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="编辑"
            placement="bottom-start"
          >
            <el-button
              type="success"
              icon="el-icon-edit"
              size="mini"
              @click="addManagerById(scope.row.id)"
            ></el-button>
          </el-tooltip>
          <!-- 删除按钮 -->
          <el-tooltip
            class="item"
            effect="dark"
            content="删除管理员"
            placement="bottom"
          >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryInfo.pagenum"
      :limit.sync="queryInfo.pagesize"
      @pagination="getRolesList"
    />

    <!-- 添加对话框 -->
    <el-dialog
      title="创建角色"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- :visible.sync属性绑定用来控制对话框的显示和隐藏 -->
      <!-- 内容主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色权限" prop="nameZh">
          <el-select v-model="addForm.nameZh" placeholder="请选择">
            <el-option
              v-for="item in option"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑权限对话框 -->
    <el-dialog
      title="添加权限"
      :visible.sync="addPowerDialogVisible"
      width="50%"
      @close="addPowerDialogClosed"
    >
      <!-- 修改权限 -->
      <el-form
        :model="addPowerForm"
        :rules="addPowerFormRules"
        ref="addPowerFormRef"
        label-width="70px"
      >
        <el-form-item label="角色名称" prop="username">
          <el-input v-model="addPowerForm.name" disabled></el-input>
        </el-form-item>
        <!-- <el-form-item label="id" prop="id">
          <el-input type="number" v-model.number="addPowerForm.id"></el-input>
        </el-form-item> -->
        <el-form-item label="角色权限" prop="id" label-width="78px">
          <el-select v-model="addPowerForm.id" placeholder="请选择">
            <el-option
              v-for="item in selectValue"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addPowerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPower">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRolesInfo,
  addRoles,
  removeManager,
  addPowers,
  searchInfo,
  getTotal
} from "@/api/roles";
import Buttons from "@/components/button/index.vue";
import Pagination from "@/components/Pagination";
import {
  addPowerFormRules,
  addFormRules,
  options,
  selectValues
} from "@/config/role/index";
import { checkPermission } from "@/utils/hasPermission";
import qs from "qs";
export default {
  name: "roles",
  components: {
    Buttons,
    Pagination
  },
  data() {
    return {
      // 获取用户列表的参数对象
      queryInfo: {
        query: "",
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 20
      },
      // 添加用户的表单数据
      addForm: {
        name: "",
        // password: "",
        nameZh: ""
      },
      // 添加管理员权限数据
      addPowerForm: [],
      addPowerDialogVisible: false,
      total: 0,
      text1: "创建角色",
      text3: "搜索",
      roleslist: [],
      // 添加表单验证规则对象
      addFormRules: {},
      // 修改管理员权限验证对象
      addPowerFormRules: {},
      addDialogVisible: false,
      role_id: 0,
      option: [],
      listLoading: false,
      selectValue: []
    };
  },
  created() {
    let self = this;
    self.addFormRules = addFormRules;
    self.addPowerFormRules = addPowerFormRules;
    self.option = options;
    self.selectValue = selectValues;
    self.getRolesList();
  },
  // mounted() {
  //   let self = this;
  //   self.getRolesList();
  // },
  methods: {
    checkPermission,
    async getRolesList() {
      let self = this;
      self.listLoading = true;
      const res = await getRolesInfo({
        page_number: self.queryInfo.pagenum,
        page_size: self.queryInfo.pagesize
      });
      self.roleslist = res.result;
      // console.log(self.roleslist);
      const response = await getTotal();
      // console.log(response);
      self.total = response.result[0].numbers;
      // let list = self.roleslist.filter((item, index) =>
      //   item.name.includes(self.queryInfo.query)
      // );
      // console.log(list);
      // self.roleslist = list.filter(
      //   (item, index) =>
      //     index < self.queryInfo.pagenum * self.queryInfo.pagesize &&
      //     index >= self.queryInfo.pagesize * (self.queryInfo.pagenum - 1)
      // );
      // console.log(res);
      // Just to simulate the time of the request
      setTimeout(() => {
        self.listLoading = false;
      }, 1.5 * 1000);
    },
    // 根据id删除对应用户信息
    async removeUserById(id) {
      if (!this.checkPermission()) return;
      // console.log(id);
      let self = this;
      // 先弹框询问用户是否删除数据
      const confirmResult = await self
        .$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .catch(err => err);
      // 如果用户确认删除则返回值为字符串 confirm
      // 如果用户取消了删除，则返回值为字符串 cancel
      // console.log(confirmResult);
      if (confirmResult !== "confirm") {
        return self.$message.info("已经取消删除");
      }

      // console.log("确认了删除");
      const res = await removeManager(id);
      if (res.code !== 1) {
        return self.$message.error("删除角色失败！");
      }

      self.$message.success("删除角色成功！");
      this.getRolesList();
    },
    // 展示添加管理员对话框
    addRoleDialog() {
      if (!this.checkPermission()) return;
      this.addDialogVisible = true;
    },
    // 点击按钮，添加新用户
    addRole() {
      let self = this;
      self.$refs.addFormRef.validate(async valid => {
        // console.log(valid);
        if (!valid) return;
        // 可以发起添加用户的网络请求
        const res = await addRoles(self.addForm);
        console.log(res);
        if (res.code !== 1) {
          return self.$message.error("添加管理员失败！");
        }

        self.$message.success("添加管理员成功！");
        // 隐藏添加用户的对话框
        self.addDialogVisible = false;
        // 重新获取用户列表数据
        self.getRolesList();
      });
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 监听修改权限对话框关闭事件
    addPowerDialogClosed() {
      this.$refs.addPowerFormRef.resetFields();
    },
    // 添加管理员权限展示对话框
    addManagerById(id) {
      // console.log(id);
      if (!this.checkPermission()) return;
      let self = this;
      // isSuperManager();
      self.addPowerForm =
        self.roleslist[self.roleslist.findIndex(res => res.id === id)];
      self.addPowerDialogVisible = true;
      console.log(self.addPowerForm);
    },
    // 确认添加
    addPower() {
      let self = this;
      self.$refs.addPowerFormRef.validate(async valid => {
        if (!valid) return;
        const res = await addPowers({
          id: self.addPowerForm.id,
          role_id: self.addPowerForm.role_id
        });
        console.log(res);
        if (res.code !== 1) {
          return self.$message.error("修改管理员权限失败！");
        }
        self.$message.success("修改管理员权限成功！");
        self.getRolesList();
        self.addPowerDialogVisible = false;
      });
    },
    // 时间格式化
    dateFormat(row, column) {
      // dateFormat();
      // console.log(row, column);
      var date = row[column.property];
      if (date == undefined) return "";
      return this.$moment.unix(date).format("YYYY-MM-DD HH:mm:ss");
    },
    // 搜索
    async searchFor() {
      let self = this;
      self.listLoading = true;
      const res = await searchInfo({
        likeName: self.queryInfo.query.trim()
      });
      console.log(res);
      setTimeout(() => {
        self.roleslist = res.result;
        self.total = self.roleslist.length;
        self.listLoading = false;
      }, 1.5 * 500);
    }
  }
};
</script>
<style lang="scss" scoped>
.search-btn {
  margin-left: 10px;
  margin-right: auto;
}
.function-lan {
  align-items: center;
}
</style>
